<template>
  <div class="login-page">
    <div class="login-container">
      <h2>用户登录</h2>
      <form @submit.prevent="handleLogin" class="login-form">
        <div class="form-group">
          <input
            v-model="form.email"
            type="text"
            placeholder="请输入用户名或邮箱"
            required
          >
        </div>
        <div class="form-group">
          <input
            v-model="form.password"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码"
            required
          >
          <button type="button" class="password-toggle" @click="showPassword = !showPassword">
            {{ showPassword ? '隐藏' : '显示' }}
          </button>
        </div>
        <button type="submit" class="login-btn" :disabled="loading">
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>
      
      <!-- 添加调试信息显示 -->
      <div class="debug-info" v-if="debugMode">
        <p>当前用户状态: {{ currentUser ? `已登录: ${currentUser.username}` : '未登录' }}</p>
        <p>localStorage user: {{ localStorageUser }}</p>
        <p>localStorage token: {{ localStorageToken }}</p>
        <p>Token Store 状态: {{ tokenStoreStatus }}</p>
      </div>
      
      <div class="login-links">
        <router-link to="/register">注册新账号</router-link>
        <router-link to="/forgot-password">忘记密码？</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/token'

const router = useRouter()
const tokenStore = useTokenStore()

const loading = ref(false)
const showPassword = ref(false)
const debugMode = ref(true) // 设置为 true 来显示调试信息
const currentUser = ref(null)

const form = reactive({
  email: '',
  password: ''
})

// 调试信息
const localStorageUser = computed(() => {
  return localStorage.getItem('user')
})

const localStorageToken = computed(() => {
  const token = localStorage.getItem('token')
  return token ? token.substring(0, 20) + '...' : '无'
})

const tokenStoreStatus = computed(() => {
  return tokenStore.hasToken ? '有Token' : '无Token'
})

const handleLogin = async () => {
  loading.value = true
  try {
    console.log('开始登录，邮箱/用户名:', form.email)
    
    // 调用真实的后端登录API
    const response = await fetch('http://localhost:3001/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: form.email,
        password: form.password
      })
    })
    
    const data = await response.json()
    console.log('后端登录响应:', data)
    
    if (data.success) {
      // 登录成功 - 使用 Token Store 保存token
      tokenStore.setToken(data.token)
      
      // 保存用户信息到 localStorage
      localStorage.setItem('user', JSON.stringify(data.user))
      currentUser.value = data.user
      
      console.log('登录成功，用户信息:', data.user)
      console.log('Token已保存到Store:', tokenStore.hasToken)
      console.log('Token值:', data.token.substring(0, 20) + '...')
      
      alert('登录成功！')
      
      // 跳转到首页 - 路由守卫会自动放行
      console.log('准备跳转到首页...')
      router.push('/')
    } else {
      alert('登录失败: ' + data.message)
    }
    
  } catch (error) {
    console.error('登录错误:', error)
    alert('网络错误，请检查后端服务器是否运行')
  } finally {
    loading.value = false
  }
}

// 检查自动登录状态
const checkAutoLogin = () => {
  const token = localStorage.getItem('token')
  const user = localStorage.getItem('user')
  
  if (token && user) {
    try {
      // 如果本地有token，也同步到Token Store
      if (token && !tokenStore.hasToken) {
        tokenStore.setToken(token)
      }
      
      currentUser.value = JSON.parse(user)
      console.log('自动登录状态: 已登录', currentUser.value)
      console.log('Token Store 同步完成:', tokenStore.hasToken)
    } catch (e) {
      console.error('解析用户信息失败:', e)
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      tokenStore.clearToken()
    }
  }
}

// 如果已经登录，自动跳转到首页
const checkIfAlreadyLoggedIn = () => {
  if (tokenStore.hasToken) {
    console.log('检测到已登录，自动跳转到首页')
    router.push('/')
  }
}

// 组件挂载时检查当前状态
onMounted(() => {
  console.log('Login组件挂载')
  console.log('Token Store 初始状态:', tokenStore.hasToken)
  console.log('localStorage token:', localStorage.getItem('token') ? '存在' : '不存在')
  
  checkAutoLogin()
  checkIfAlreadyLoggedIn()
  
  console.log('当前用户状态:', currentUser.value)
  console.log('localStorage user:', localStorage.getItem('user'))
})
</script>

<style scoped>
.login-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 80vh;
  padding: 20px;
}

.login-container {
  width: 100%;
  max-width: 400px;
  background: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.login-container h2 {
  text-align: center;
  margin-bottom: 2rem;
  color: #333;
}

.form-group {
  position: relative;
  margin-bottom: 1.5rem;
}

.form-group input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  border-color: #007bff;
}

.password-toggle {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  font-size: 12px;
}

.login-btn {
  width: 100%;
  padding: 12px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s;
}

.login-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.login-btn:hover:not(:disabled) {
  background: #0056b3;
}

.login-links {
  display: flex;
  justify-content: space-between;
  margin-top: 1rem;
  font-size: 14px;
}

.login-links a {
  color: #007bff;
  text-decoration: none;
}

.login-links a:hover {
  text-decoration: underline;
}

/* 调试信息样式 */
.debug-info {
  margin-top: 1rem;
  padding: 1rem;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #007bff;
}

.debug-info p {
  margin: 0.5rem 0;
  font-size: 12px;
  color: #666;
  font-family: monospace;
}
</style>